package com.shinemo.mpush.alloc.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import com.mpush.api.Constants;
import com.mpush.tools.Jsons;
import com.mpush.tools.config.CC;
import com.shinemo.mpush.alloc.exception.EmptySignSecretHeaderException;
import com.shinemo.mpush.alloc.exception.InvalidSignSecretHeaderException;
import com.shinemo.mpush.alloc.exception.SignHeaderException;
import com.sun.net.httpserver.HttpExchange;

public class HttpRequest {
	
	private HttpRequest() {}
	
	public static Map<String, Object> getParameters(HttpExchange httpExchange) throws IOException {
		return getParameters(httpExchange,Constants.UTF_8);
	}
	
	public static Map<String, Object> getParameters(HttpExchange httpExchange,Charset charset) throws IOException {
		String body = readBody(httpExchange,charset);
		
		 return Jsons.fromJson(body, Map.class);
	}
	
	public static Map<String, Object> toMap(String body){
		 return Jsons.fromJson(body, Map.class);
	}
	
	public static String getBody(HttpExchange httpExchange) throws IOException {
		return readBody(httpExchange,Constants.UTF_8);
	}
	
	public static String readBody(HttpExchange httpExchange,Charset charset) throws IOException {
		return new String(readByte(httpExchange), charset);
	}

	public static String getSignHeader(HttpExchange httpExchange){
		return httpExchange.getResponseHeaders().getFirst("sign-secret");
	}

	/*
	 * 检查签名头是否有效，无效抛出异常
	 * @param httpExchange
	 * @return
	 * @throws SignHeaderException
	 */
	public boolean checkSignHeader(HttpExchange httpExchange) throws SignHeaderException {
		String signSecretHeader = httpExchange.getResponseHeaders().getFirst("sign-secret");

		if(null==signSecretHeader || "".equals(signSecretHeader)){
			throw new EmptySignSecretHeaderException();
		}

		if(!CC.mp.api.signSecret.equals(signSecretHeader)){
			throw new InvalidSignSecretHeaderException();
		}

		return true;
	}

	private static byte[] readByte(HttpExchange httpExchange) throws IOException {
		InputStream in = httpExchange.getRequestBody();
		String length = httpExchange.getRequestHeaders().getFirst("content-length");
		if (length != null && !length.equals("0")) {
			byte[] buffer = new byte[Integer.parseInt(length)];
			in.read(buffer);
			in.close();
			return buffer;
		} else {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			in.close();
			return out.toByteArray();
		}
	}
	
}
